package com.github.livebase.storage;

import com.github.livebase.database.StorageOperator;
import com.github.livebase.util.base.DateUtil;

/**
 * @ClassName LStorage
 * @description:
 * @author: biao532
 * @create: 2024-02-19 11:40
 * @Version 1.0
 **/
public class LStorage implements LocalStorage {
    private String owner;
    private int version;
    private Converter converter;
    private StorageOperator op;

    public LStorage(String owner, int version, Converter converter, StorageOperator op) {
        this.owner = owner;
        this.version = version;
        this.converter = converter;
        this.op = op;
    }

    @Override
    public <T> T get(String key) {
        StorageOperator.StorageEntity storageEntity = op.get(key, owner, version);
        try {
            return converter.fromString(storageEntity);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public <T> T get(String key, T defaultValue) {
        T t = get(key);
        if (t == null) {
            return defaultValue;
        }
        return t;
    }

    @Override
    public <T> boolean put(String key, T value) {
        return put(key, value, -1);
    }

    @Override
    public <T> boolean put(String key, T value, long expire) {
        byte[] bs = converter.toString(value);
        StorageOperator.StorageEntity entity = new StorageOperator.StorageEntity(owner, key, version, bs, value.getClass().getName(), DateUtil.now()+expire);
        if (expire < 0) {
            entity.setExpire(-1);
        }
        op.upsert(entity);
        return true;
    }

    @Override
    public boolean delete(String key) {
        return op.delete(key, owner) > 0;
    }

    @Override
    public boolean contains(String key) {
        return op.exist(key, owner, version);
    }

    @Override
    public boolean clear() {
        return op.delete(owner) != 0;
    }

    public boolean deleteByKeyPrefix(String prefix) {
        return op.deleteByKeyPrefix(prefix, owner) > 0;
    }
}
